<?php
header('Content-Type: application/json');

try {
    // 检查必要参数和文件
    if (!isset($_POST['id']) || !isset($_POST['page']) || !isset($_FILES['image']) || !isset($_FILES['thumb'])) {
        throw new Exception('参数错误');
    }

    $bookId = $_POST['id'];
    $page = $_POST['page'];
    $pageFile = $_FILES['image'];
    $thumbFile = $_FILES['thumb'];


    if ($page == 1) {
        // rmdir(../../uploads/books/1/pages): Directory not empty

        // 清空目录
        $normalPath = "../../uploads/books/{$bookId}/pages";
        $thumbPath = "../../uploads/books/{$bookId}/thumb";
        if (file_exists($normalPath)) {
            deleteDir($normalPath);  // 使用删除目录内容的函数
        }
    }

    // 创建目录（如果不存在）
    $dirs = [
        "../../uploads/books/{$bookId}/pages",
        "../../uploads/books/{$bookId}/thumb"
    ];
    foreach ($dirs as $dir) {
        if (!file_exists($dir)) {
            mkdir($dir, 0777, true);
        }
    }


    // 处理正常尺寸图片
    $normalPath = "../../uploads/books/{$bookId}/pages/{$page}.jpg";
    if (!move_uploaded_file($pageFile['tmp_name'], $normalPath)) {
        throw new Exception('保存正常图片失败');
    }

    // 处理缩略图
    $thumbPath = "../../uploads/books/{$bookId}/thumb/{$page}.jpg";
    if (!move_uploaded_file($thumbFile['tmp_name'], $thumbPath)) {
        throw new Exception('保存缩略图失败');
    }

    // 返回成功信息
    echo json_encode([
        'success' => true,
        'urls' => [
            'normal' => str_replace('../../', '/admin/', $normalPath),
            'thumb' => str_replace('../../', '/admin/', $thumbPath)
        ]
    ]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}


function deleteDir($dirPath)
{
    if (!is_dir($dirPath)) {
        return false;  // 如果路径不是目录，直接返回
    }

    $files = array_diff(scandir($dirPath), array('.', '..')); // 获取目录中的所有文件和子目录

    foreach ($files as $file) {
        $filePath = $dirPath . DIRECTORY_SEPARATOR . $file;
        if (is_dir($filePath)) {
            deleteDir($filePath); // 递归删除子目录
        } else {
            unlink($filePath); // 删除文件
        }
    }

    rmdir($dirPath); // 删除空目录
    return true;
}
